package com.jf.cloud.service.sysmanager.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Crypter {
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	private MessageDigest mdInstance = null;
	


	public MD5Crypter() {
		try {
			mdInstance = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			//
		}
	}

	private String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();

		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}

		return resultSb.toString();
	}

	private String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}

		int d1 = n / 16;
		int d2 = n % 16;

		return hexDigits[d1] + hexDigits[d2];
	}

	public String encode(final String origin) {
		return byteArrayToHexString(mdInstance.digest(origin.getBytes()));
	}
    /**
     * 对原始字符串 转换为 64位密文【未经过处理的明文】
     */
	public String encodeBy64Md5(String str){
		if (str==null || str.length()==0) {
			throw new RuntimeException("参数不正确");
		}
		String md5 = encode(str);
		return encodeMd5to64(md5);
	}	
	/**
	 * 对 已经通过md5的字符串 转换为 64位密文
	 * 兼容 老站数据转移
	 */
	public String encodeMd5to64(String str){
		if (str==null || str.length()==0) {
			throw new RuntimeException("参数不正确");
		}
		String md5 = str;
		String salt = md5.substring(16, md5.length());
		salt =new StringBuffer(salt).reverse().toString();
		return Base64.getBASE64(md5+salt);
	}	
	/**
	 * 原有加密方法
	 * str：原字符串
	 * webSiteKey：附加字符串
	 */
	public String encodeBy64Md5(String str, String webSiteKey){
		if (str==null || str.length()==0) {
			throw new RuntimeException("参数不正确");
		}
		String md5 = encode(str+webSiteKey);
		String salt = md5.substring(16, md5.length());
		salt =new StringBuffer(salt).reverse().toString();
		return Base64.getBASE64(md5+salt);
	}
	
	public String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
			if (n < b.length - 1) {
				hs = hs + ":";
			}
		}
		return hs.toUpperCase();
	}
}
